﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using LuaInterface;
using LitJson;

public class GetLocationData : MonoBehaviour {
 
	public static string FURL="https://api.map.baidu.com/reverse_geocoding/v3/?ak=SfrwGH7INvjPq7BwCrYrioBQZm9XXxrR&output=json&coordtype=wgs84ll&extensions_town=true&location={0},{1}";
    public Action OnGetLocationDataOKEvent;
 
    public static string url = "https://api.map.baidu.com/location/ip?ak=bretF4dm6W5gqjQAXuvP0NXW6FeesRXb&coor=bd09ll";

	public static GetLocationData Instance=null;
 
    void Start()
    {
        StartCoroutine(Request());
    }

	public static GetLocationData GetInstance()
	{
		if(Instance==null)
		{
			Instance=new GetLocationData();
		}
		return Instance;
	}
 
    public void GetLocationDataNoGPS() {
        StartCoroutine(Request());
    }
 
    public static IEnumerator Request()
    {
        // 判断是否有网络 更具需要处理是否连续判断是否有网
        while (Application.internetReachability == NetworkReachability.NotReachable) {
            Debug.Log("正在连接网络");
           yield return new WaitForSeconds(1.0f);
        }

		UnityWebRequest webRequest = UnityWebRequest.Get(url);

        yield return webRequest.SendWebRequest();
        //异常处理，很多博文用了error!=null这是错误的，请看下文其他属性部分
       if (webRequest.isHttpError||webRequest.isNetworkError)
            Debug.Log(webRequest.error);
        else 
        {
            if (webRequest.downloadHandler.text.ToLower().Contains("Error".ToLower()) == false)
            {
				ResponseBody req = null;
				try {
					req = JsonMapper.ToObject<ResponseBody>(webRequest.downloadHandler.text);
				} catch(Exception e)
				{
					Debug.LogError(e.StackTrace);
				}
				var content = req?.content;
				//Debug.Log(ArrowBLEDebugHelper.DEBUGMARK + StringUnicodeHelper.UnicodeToString(req.content.address_detail.city) +" X: "+ req.content.point.x +" Y: "+ req.content.point.x);
				//Debug.Log("省"+req.content.address_detail.province+"市"+req.content.address_detail.city+"区"+req.content.address_detail.district + " X: " + req.content.point.x + " Y: " + req.content.point.y);
				if (content == null || content.address_detail == null)
				{
					Debug.LogError("请求lbs错误："+ webRequest.downloadHandler.text);
				}
				else {
					var detail = content.address_detail;
					string province = detail.province.ToString();
					Debug.Log("location:"+ province);
					LBSLocation.SetLocationDataGPS( province);
				}
                //StartCoroutine(GetRealLocation(req.content.point.y,req.content.point.x));
            }
            else
            {
                Debug.Log( " 局域网，或者虚假连接网络");
            }			
        }
    }

	public static IEnumerator GetRealLocation(string y,string x)
	{
		string checkPath=string.Format(FURL,y,x);
		UnityWebRequest webRequest = UnityWebRequest.Get(checkPath);

        yield return webRequest.SendWebRequest();
        //异常处理，很多博文用了error!=null这是错误的，请看下文其他属性部分
       if (webRequest.isHttpError||webRequest.isNetworkError)
            Debug.Log(webRequest.error);
        else 
        {
 
            Debug.Log(webRequest.downloadHandler.text);
 
            if (webRequest.downloadHandler.text.ToLower().Contains("Error".ToLower()) == false)
            {
				ResponseBodyComp req = null;
				try
				{
					req = JsonMapper.ToObject<ResponseBodyComp>(webRequest.downloadHandler.text);
				}
				catch(Exception e)
				{
					Debug.LogError(e.StackTrace);
				}
				string PosAdress = "";
				if (req != null)
				{
					PosAdress = req.result.addressComponent.city + req.result.addressComponent.district;
					if (req.result.addressComponent.province == req.result.addressComponent.city)
					{
						PosAdress = req.result.addressComponent.city + req.result.addressComponent.district;
					}
					else
					{
						PosAdress = req.result.addressComponent.province + req.result.addressComponent.city + req.result.addressComponent.district;
					}
				}
                LBSLocation.SetLocationDataGPS( PosAdress);
				// if(callback!=null)
				// {
				// 	callback.Call(PosAdress);
				// 	PosAdress="";
				// }				
                //Debug.Log(ArrowBLEDebugHelper.DEBUGMARK + StringUnicodeHelper.UnicodeToString(req.content.address_detail.city) +" X: "+ req.content.point.x +" Y: "+ req.content.point.x)
                //Debug.LogError("省"+req.result.addressComponent.province+"市"+req.result.addressComponent.city);
            }
            else
            {
                Debug.Log( " 局域网，或者虚假连接网络");
            }
 
        }
	}
}
 
 
public class ResponseBody
{
 
    public string address;
    public Content content;
    public int status;
 
}

public class ResponseBodyComp
{
 
    //public string address;
    public result result;
    public int status;
 
}

[SerializeField]
public class Content
{
    public string address;
    public Address_Detail address_detail;
    public Point point;
}

[SerializeField]
public class result
{
    //public string address;
    public addressComponent addressComponent;
    //public Point point;
}

[SerializeField]
public class addressComponent
{
	public string country;
    public string city;
    public string city_code;
    public string district;
    public string province;
    public string street;
    public addressComponent() { }
    public addressComponent(string country,string city, string city_code, string district, string province, string street)
    {
		this.country=country;
        this.city = city;
        this.city_code = city_code;
        this.district = district;
        this.province = province;
        this.street = street;
    }
}

[SerializeField]
public class Address_Detail
{
    public string city;
    public int city_code;
    public string district;
    public string province;
    public string street;
    public string street_number;
    public Address_Detail() { }
    public Address_Detail(string city, int city_code, string district, string province, string street, string street_number)
    { 
        this.city = city;
        this.city_code = city_code;
        this.district = district;
        this.province = province;
        this.street = street;
        this.street_number = street_number;
    }
}
[SerializeField]
public class Point
{
    public string x;
    public string y;
    public Point() { }
    public Point(string x, string y)
    {
        this.x = x;
        this.y = y;
    }
}
 
public class StringUnicodeHelper{
    /// <summary>
    /// 字符串转Unicode码
    /// </summary>
    /// <returns>The to unicode.</returns>
    /// <param name="value">Value.</param>
    public static string StringToUnicode(string value)
    {
        byte[] bytes = Encoding.Unicode.GetBytes(value);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < bytes.Length; i += 2)
        {
            // 取两个字符，每个字符都是右对齐。
            stringBuilder.AppendFormat("u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
        }
        return stringBuilder.ToString();
    }
 
    /// <summary>
    /// Unicode转字符串
    /// </summary>
    /// <returns>The to string.</returns>
    /// <param name="unicode">Unicode.</param>
    public static string UnicodeToString(string unicode)
    {
        string resultStr = "";
        string[] strList = unicode.Split('u');
        for (int i = 1; i < strList.Length; i++)
        {
            resultStr += (char)int.Parse(strList[i], System.Globalization.NumberStyles.HexNumber);
        }
        return resultStr;
    }
 
    
}